package com.swpu.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swpu.project.common.BaseResponse;
import com.swpu.project.mapper.SecondaryMapper;
import com.swpu.project.model.dto.data.DataEntity;
import com.swpu.project.model.dto.data.DataEntityDto;
import com.swpu.project.model.entity.*;
import com.swpu.project.model.page.PageDto;
import com.swpu.project.model.page.PageQuery;
import com.swpu.project.service.IHeavyMetalService;
import com.swpu.project.service.IMineralService;
import com.swpu.project.service.INonHeavyMetalService;
import com.swpu.project.service.ISecondaryService;
import com.swpu.project.strategy.FilterContext;
import com.swpu.project.util.NumberUtil;
import com.swpu.project.util.XlxsDataType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author swpuyanxiegroup1
 * @since 2024-07-29
 */
@Service
public class SecondaryServiceImpl extends ServiceImpl<SecondaryMapper, Secondary> implements ISecondaryService {


    @Resource
    IHeavyMetalService iHeavyMetalService;
    @Resource
    INonHeavyMetalService iNonHeavyMetalService;
    @Resource
    IMineralService iMineralService;
    @Resource
    SecondaryMapper secondaryMapper;
    @Override
    public BaseResponse addData(DataEntityDto dataEntityDto) {
        DataEntity dataEntity = dataEntityDto.getDataEntity();
        if(!checkAuthority(dataEntity))
            return BaseResponse.fail("您不具有该操作的权限");

        Secondary secondary = BeanUtil.copyProperties(dataEntity, Secondary.class);
        boolean save = save(secondary);
        addInform(dataEntityDto);
        return BaseResponse.iFSuccess(save);
    }

    @Override
    public BaseResponse   pageQuery(PageQuery pageQuery)
    {
        LambdaQueryWrapper<Secondary> nativeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        Map<String, String> queryBy = pageQuery.getQueryBy();
        if(queryBy!=null) {
            String blockNum = queryBy.get("blockName");

            if (StrUtil.isNotBlank(blockNum)) {
                if (!setValidBlock(nativeLambdaQueryWrapper, blockNum))
                    return BaseResponse.fail("筛选条件有误");

            } else {
                setBlockCondition(nativeLambdaQueryWrapper);
            }
            queryBy.remove("blockName");
            if (!queryBy.isEmpty())
                setOtherCondtion(nativeLambdaQueryWrapper, queryBy);

        }


        Page page = setPage(pageQuery);
        page(page, nativeLambdaQueryWrapper);
        PageDto nativePageDto = new PageDto(page);
        return BaseResponse.ok(nativePageDto);

    }

    private Page setPage(PageQuery pageQuery) {
        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        Page<Native> page = Page.of(pageNum, pageSize);
        pageQuery.initSortBy(page);


        return page;

    }
    void setBlockCondition(LambdaQueryWrapper<Secondary> lambdaQueryWrapper)
    {
        LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> blockNums = principal.getBlockNums();

        lambdaQueryWrapper.and(lambdaQueryWrapper1 -> {

                    for (int i = 0; i <blockNums.size() ; i++) {
                        String s = blockNums.get(i);
                        s=s+"号区块";
                        lambdaQueryWrapper1.eq(Secondary::getBlockName,s);
                        if(i != blockNums.size()-1)
                            lambdaQueryWrapper1.or();
                    }
                }
        );

    }
    private void setOtherCondtion(LambdaQueryWrapper<Secondary> nativeLambdaQueryWrapper, Map<String, String> queryBy)
    {
        FilterContext filterContext =  FilterContext.getConText(XlxsDataType.SECONDARY);
        filterContext.makeFilterCondtion(nativeLambdaQueryWrapper,queryBy);

    }


    private Boolean setValidBlock(LambdaQueryWrapper<Secondary> nativeLambdaQueryWrapper,String blockNum)
    {
        LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> blockNums = principal.getBlockNums();
        blockNum= NumberUtil.findNumber(blockNum);
        if(blockNum==null)
            return false;


        if(!blockNum.contains(blockNum))
            return false;

        nativeLambdaQueryWrapper.likeRight(Secondary::getBlockName,blockNum);

        return true;
    }

    @Override
    public BaseResponse updateData(Secondary secondary) {
        if(!checkAuthority(secondary))
            return BaseResponse.fail("您不具有进行该搞作的权限");




        return BaseResponse.iFSuccess(updateById(secondary));
    }

    @Override
    public BaseResponse querySecondary()
    {   LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> blockNums = principal.getBlockNums();

        LambdaUpdateWrapper<Secondary> secondaryLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        for (int i = 0; i <blockNums.size() ; i++) {
            String s = blockNums.get(i);
            s=s+"号区块";
            secondaryLambdaUpdateWrapper.eq(Secondary::getBlockName,s);
           if(i!=blockNums.size()-1)
               secondaryLambdaUpdateWrapper.or();

        }

        return new BaseResponse(201,secondaryMapper.selectList(secondaryLambdaUpdateWrapper));
    }






    /*

    为了节省响应时间,要求前端传所有数据过来一次性全部初始化
    * */
    public  void addInform(DataEntityDto dataEntityDto)
    {
        List<HeavyMetal> heavyMetals = dataEntityDto.getHeavyMetals();
        List<NonHeavyMetal> nonHeavyMetals = dataEntityDto.getNonHeavyMetals();
        List<Mineral> minerals = dataEntityDto.getMinerals();
        iHeavyMetalService.saveBatch(heavyMetals);
        iNonHeavyMetalService.saveBatch(nonHeavyMetals);
        iMineralService.saveBatch(minerals);


    }

    Boolean checkAuthority(Secondary secondary)
    {   LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> blockNums = principal.getBlockNums();
        String blockName = secondary.getBlockName();
        String number = NumberUtil.findNumber(blockName);
        if(!blockNums.contains(number))
            return false;

        blockName=number+"号区块";
      secondary.setBlockName(blockName);

        return true;


    }


    Boolean checkAuthority(DataEntity dataEntity)
    {   LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> blockNums = principal.getBlockNums();
        String blockName = dataEntity.getBlockName();


        String number = NumberUtil.findNumber(blockName);


        if(!blockNums.contains(number))
            return false;
        blockName=number+"号区块";
        dataEntity.setBlockName(blockName);

        return true;


    }




}
